<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta name="full-screen" content="yes">
    <meta content="default" name="apple-mobile-web-app-status-bar-style">
    <meta name="screen-orientation" content="portrait">
    <meta name="browsermode" content="application">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="x5-orientation" content="portrait">
    <meta name="x5-fullscreen" content="true">
    <meta name="x5-page-mode" content="app">
    <base target="_blank">
    <title>在线聊天室</title>
    <link href="./dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="./dist/css/chat.css">
    <style>
        body {
           /* background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%); */
        }
    </style>
</head>

<body>
<!--<img style="width:100%;height:100%" src="img/chat_bg.jpg">-->


<div class="abs cover contaniner" id="app">
    <div class="abs cover pnl">
        <div class="top pnl-head" style="padding: 20px ; color: white;">
            <div id="userName">
                用户：{{toName}}
                <span style='float: right;color: green' v-if="isOnline">在线</span>
                <span style='float: right;color: red' v-else>离线</span>
            </div>
            <div id="chatMes" v-show="chatMes" style="text-align: center;color: #6fbdf3;font-family: 新宋体">
                正在和 <font face="楷体">{{toName}}</font> 聊天
            </div>
        </div>
        <!--聊天区开始-->
        <div class="abs cover pnl-body" id="pnlBody">
            <div class="abs cover pnl-left" id="initBackground" style="background-color: white; width: 100%">
                <!-- <div class="abs cover pnl-left" id="chatArea" v-show="isShowChat"> -->
				<div class="abs cover pnl-left" id="chatArea">
                    <div class="abs cover pnl-msgs scroll" id="show">
                        <div class="pnl-list" id="hists">
							<!-- 历史消息 -->
						
						</div>
                        <div class="pnl-list" id="msgs" v-for="message in historyMessage">

                            <!-- 消息这展示区域 -->
                            <!-- <div class="msg guest" v-if="message.toName">
                                <div class="msg-right">
                                    <div class="msg-host headDefault" 
                                         style="background-image: url();"></div>
                                    <div class="msg-ball">{{message.message}}</div>
                                </div>
                            </div>
                            <div class="msg robot" v-else>
                                <div class="msg-left" worker="">
                                    <div class="msg-host photo"
                                         style="background-image: url(img/avatar/Member002.jpg)"></div>
                                    <div class="msg-ball">{{message.message}}</div>
                                </div>
                            </div> -->

                            <div class="msg guest" v-if="message.toName">
                                <div class="msg-right">
                                    <div class="msg-host headDefault" 
                                         :style="{ backgroundImage: 'url(' + userImg + ')' }"></div>
                                    <div class="msg-ball">{{ message.message }}</div>
                                </div>
                            </div>
                            <div class="msg robot" v-else>
                                <div class="msg-left" worker="">
                                    <div class="msg-host photo"
                                         :style="{ backgroundImage: 'url(' + toUserImg + ')' }"></div>
                                    <div class="msg-ball">{{ message.message }}</div>
                                </div>
                            </div>
                            

                        </div>
                    </div>



                    <div class="abs bottom pnl-text">
                        <div class="abs cover pnl-input">
                            <textarea class="scroll" id="context_text" @keyup.enter="submit" wrap="hard" placeholder="在此输入文字信息..."
                                      v-model="sendMessage.message"></textarea>
                            <div class="abs atcom-pnl scroll hide" id="atcomPnl">
                                <ul class="atcom" id="atcom"></ul>
                            </div>
                        </div>

                        <div class="abs br pnl-btn" id="submit" @click="submit"
                             style="background-color: rgb(32, 196, 202); color: rgb(255, 255, 255);">
                            发送
                        </div>
                        <div class="pnl-support" id="copyright"><a href="https://blog.csdn.net/LEE180501?spm=1000.2115.3001.5343">仅供学习参考</a></div>
                    </div>
                </div>

                <!--聊天区 结束-->
                <div class="abs right pnl-right">
                    <div class="slider-container hide"></div>
<!--                    <div class="pnl-right-content">
                        <div class="pnl-tabs">
                            <div class="tab-btn active" id="hot-tab">好友列表</div>
                        </div>
                        <div class="pnl-hot">
                            <ul class="rel-list unselect">
                                <li class="rel-item" v-for="friend in friendsList"><a @click='showChat(friend)'>{{friend}}</a>
                                </li>
                            </ul>
                        </div>
                    </div> -->

                    <div class="pnl-right-content">
                        <div class="pnl-tabs">
                            <div class="tab-btn active">系统广播</div>
                        </div>
                        <div class="pnl-hot">
                            <ul class="rel-list unselect" id="broadcastList">
                                <li class="rel-item" style="color: #9d9d9d;font-family: 宋体" v-for="name in systemMessages">
                                    {{name}} </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="./dist/js/vue.js"></script>
<script src="./dist/js/axios-0.18.0.js"></script>
<script src="./js/urlutils.js"></script>

<script>
    var id = getParamValue("userid");
    let ws;
    new Vue({
        el: "#app",
        data() {
            return {
                // isShowChat: false,
                chatMes: true,
                isOnline: false,
                username:"",
                userImg:"./image/avatar02.jpeg",
                toName: "",
                toUserImg:"./image/avatar03.jpeg",
                sendMessage: {
                    id: "",
                    toName: "",
                    message: ""
                },
                inputMessage: "",
                historyMessage: [

                ],
                friendsList: [

                ],
                systemMessages : [

                ]
            }
        },
        created() {
            this.init();
        },
        // mounted() {
        //     // 整个生命周期只执行一次
        //     this.createWebSocket();
        // },
        methods: {
            async init() {
                await axios.get("user/getUserInfo").then(res => {
                    console.log(res.data.data);
                    this.username = res.data.data.nickname;
                    // 头像保底策略
                    if (res.data.data.avatarUrl) {
                        this.userImg = res.data.data.avatarUrl;
                    }
                });
                await axios.get("user/getToUserInfo?id="+id).then(res => {
                    // this.toName = res.message;
                    // showChat(this.toName);
                    this.toName = res.data.data.nickname;
                    // 头像保底策略
                    if (res.data.data.avatarUrl) {
                        this.toUserImg = res.data.data.avatarUrl;
                    }
                    // 这里踩了个大坑，js也讲究字符串和boolean："false"和false不是一回事！！！
                    if (res.data.message == "false") {
                        this.isOnline = false;
                    } else {
                        this.isOnline = true;
                    }
                    
                    // console.log("在线状态");
                    // console.log(res.data.message);

                //清除聊天区的数据(预留，暂时用不到)
                // let history = sessionStorage.getItem(this.toName);
                // if (!history) {
                //     this.historyMessage = [];
                // } else {
                //     this.historyMessage = JSON.parse(history);
                // }
                //展示聊天对话框
                // this.isShowChat = true;
                //显示“正在和谁聊天”
                this.chatMes = true;
                });

                await axios.get("message/gethistory?receiveUserId="+id).then(res => {
                    console.log("持久化显示执行一次！");
                    this.historyMessage = [];

                    let messages = res.data.data;
                    for (let i = 0; i < messages.length; i++) {
                        let message = messages[i];
                        // var history = sessionStorage.getItem(this.toName);
                        if (message.postUser.nickname == this.toName) {
                            // 说明对于当前用户来说属于发信人，将消息处理成toName=undefine的格式
                            // console.log("打印一下姓名：")
                            // console.log(res.toName);
                            let msg = {
                                fromName: message.postUser.nickname,
                                message: message.content
                            };
      
                            this.historyMessage.push(msg);
                            // sessionStorage.setItem(res.fromName, JSON.stringify(this.historyMessage));

                    

                        } else {
                            // 否则属于当前用户，将消息处理成toName != undefined的格式
                            // this.sendMessage.id = id;
                            this.sendMessage.toName = this.toName;
                            this.sendMessage.message = message.content;
                            this.historyMessage.push(JSON.parse(JSON.stringify(this.sendMessage)));

                            this.sendMessage.message = "";

                        }
                    }

                });

                //创建webSocket对象
                // 生产环境
                // ws = new WebSocket("ws://118.25.26.147:58080/chat");
                // 开发环境
                ws = new WebSocket("ws://127.0.0.1:58080/chat");


                //给ws绑定事件
                ws.onopen = this.onopen;
                //接收到服务端推送的消息后触发
                ws.onmessage = this.onMessage;

                ws.onclose = this.onClose;

                // 打印调试日志
                console.log("当前用户："+this.username);
                console.log("postUser："+this.toName);

            },
            // createWebSocket() {
            //     //创建webSocket对象
            //     ws = new WebSocket("ws://127.0.0.1:58080/chat");
            //     // ws = new WebSocket("ws://118.25.26.147:8088/chat");

            //     //给ws绑定事件
            //     ws.onopen = this.onopen;
            //     //接收到服务端推送的消息后触发
            //     ws.onmessage = this.onMessage;

            //     ws.onclose = this.onClose;

            //     // 打印调试日志
            //     // console.log("当前用户："+this.username);
            //     // console.log("postUser："+this.toName);
            // },
            showChat(name) {
                this.toName = name;
                //清除聊天区的数据
                let history = sessionStorage.getItem(this.toName);
                if (!history) {
                    this.historyMessage = [];
                } else {
                    this.historyMessage = JSON.parse(history);
                }
                //展示聊天对话框
                // this.isShowChat = true;
                //显示“正在和谁聊天”
                this.chatMes = true;
// <!--                调试代码                  -->
// <!--                console.log("sessionStorage仓库如下：");-->
// <!--                console.log(sessionStorage);-->
// <!--                console.log("toName为：");-->
// <!--                console.log(this.toName);-->
// <!--                console.log("historyMessage为：");-->
// <!--                console.log(this.historyMessage);-->
            },
            submit() {
                this.sendMessage.id = id;
                this.sendMessage.toName = this.toName;
                this.historyMessage.push(JSON.parse(JSON.stringify(this.sendMessage)));
                sessionStorage.setItem(this.toName, JSON.stringify(this.historyMessage));
                ws.send(JSON.stringify(this.sendMessage));
                this.sendMessage.message = "";
            },
            onOpen() {
                this.isOnline = false;
            },
            onClose() {
                sessionStorage.clear();
                this.isOnline = false;
                console.log("关闭执行一次！");

            },
            onMessage(evt) {
                //获取服务端推送过来的消息
                var dataStr = evt.data;
                //将dataStr 转换为json对象
                var res = JSON.parse(dataStr);
                // 收到的服务器推送消息
                console.log("收到的服务器推送消息");
                console.log(res);


                //判断是否是系统消息
                if(res.system) {
                    //系统消息
                    var name = res.message;
                    console.log("进来了");

                    console.log("name="+name);
                    console.log("username="+this.username);

                    if(name != this.username && !res.dead) {
                            // this.friendsList.push(names[i]);
                            this.systemMessages.push(name+" 已上线");

                            // 如果聊着聊着突然上线了，将状态改为在线
                        if(name == this.toName && !this.isOnline) {
                            // 
                            this.isOnline = true;

                        }

                    }

                    
                    if(name != this.username && res.dead) {
                            // this.friendsList.push(names[i]);
                            this.systemMessages.push(name+" 已离线");
                                            // 如果聊着聊着突然下线了，将状态改为下线
                        if (name == this.toName && this.isOnline) {
                            this.isOnline = false;
                        }
                    }

                }else {
                    // 当前的设计，这一步也可以简化，就没必要考虑消息隔离的问题了---
                    //非系统消息
                    // var history = sessionStorage.getItem(res.fromName);
                    if (res.fromName == this.toName) {
                        this.historyMessage.push(res);
                    }    


                }
            }
        }
    });


</script>
</body>
</html>